#include "MainHeader.h"
int lol;

BOOL CALLBACK  TextEditorProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){

	u8 Width=0;
	u8 Height=0;
	u32 Offset=0;
	switch (message) 
	{
		case WM_INITDIALOG:
			TextEditor.tMain = hWnd;

			break;
		case WM_COMMAND:
            	switch(LOWORD(wParam)){
					case WM_DESTROY:
						
					  ShowWindow(hWnd,SW_HIDE);
					break;
					case lstOffsets:
						if(HIWORD(wParam)==LBN_SELCHANGE){//LBN_DBLCLK) 
							lol =  (int)TextEditor.Text.pixels;
							if(GameEngine->isZM()){
                                Offset=TextEditor.ZMOffsets[TextEditor.cboTxt.GetListIndex()][TextEditor.cOffsets.GetListIndex()]-0x8000000;
							}else if(GameEngine->isMF()){
                                Offset=TextEditor.Offsets[TextEditor.cOffsets.GetListIndex()]-0x8000000;
							} 
							if(lol!=(int)TextEditor.Text.pixels)
								lol= lol;
					       TextEditor.DecodeText(Offset);
						   if(lol!=(int)TextEditor.Text.pixels)
								lol= lol;
                           TextEditor.Draw();
						}
						break;
					case cmdSaveText:
						/*	if(GameEngine->isZM()){
                                Offset=TextEditor.ZMOffsets[TextEditor.cboTxt.GetListIndex()][TextEditor.cOffsets.GetListIndex()]-0x8000000;
							}else if(GameEngine->isMF()){
                                Offset=TextEditor.Offsets[TextEditor.cOffsets.GetListIndex()]-0x8000000;
							} */
						TextEditor.EncodeText();
					    SendMessage(hWnd,WM_COMMAND,0x0001047a,0);
						break;
					case cboTextI:
                         TextEditor.ResetList();
						break;
				}
			break;
	}
	
	//	return DefWindowProc(hWnd, message, wParam, lParam);
	return 0;
}
cTED::cTED(){

}

cTED::~cTED(){
//	delete[] curtext;

}
int cTED::Draw(){
int X=0;
int Y=0;
int cY=0;
int cX=0;
u16 tTile=0;
int i=0;
char Color=-1;
Text.Clear();

pixelflag=-1;
for(i = 0;i<txtlength;i++){

tTile = binarystring[i];
if (tTile == 0xFE00){//New line
    Y+= 0x10;
    X = 0;
}else{
    //X += 7;

		//if( ((Tile > 0x4FF) || (Tile < 0x400))){
			if ((tTile >= 0x8100 && tTile < 0x8111)) {
        
           // Color = ((Tile)&0xf)*0x1000;
		    Color=(tTile)&0xf;
			if(Color==0)Color=-1;
            
			} else if (tTile >= 0x200 && tTile < 0x1000) {
            X += 7;
			Text.Draw(Tiles,  X, Y,  tTile);
			Text.Draw(Tiles,  X, Y+8,  tTile+ 32);
			Text.Draw(Tiles,  X+8, Y,  tTile+1);
			Text.Draw(Tiles,  X+8, Y+8, tTile+33);
            X += 7;
			}else if  (tTile < 0x100){
			 X += 7;
            Text.Draw(Tiles,  X, Y,     tTile    ,Color);
			Text.Draw(Tiles,  X, Y+8,   tTile+ 32,Color);
             
			}
	//	}
		
}



}
InvalidateRect(textpic,0,1);
	return 0;
}



int cTED::CreateTextpicTileImage(){
	WNDCLASSEX blab5;
	memset(&blab5,0,sizeof(blab5));
	blab5.cbSize = sizeof(blab5);		   // size of structure 
	blab5.style = CS_HREDRAW | 
		CS_VREDRAW; 				   // redraw if size changes 
	blab5.lpfnWndProc = &TextPicProc;	  // points to window procedure 
	blab5.cbClsExtra = NULL;				// no extra class memory 
	blab5.cbWndExtra =NULL; 			   // no extra window memory 
	blab5.hInstance = hGlobal;		   // handle to instance 
	blab5.hIcon = NULL; 			 // predefined app. icon 
	blab5.hCursor = NULL;				// predefined arrow 
	//blab5.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH);				   // white background brush 
	blab5.lpszMenuName =  NULL;    // name of menu resource 
	blab5.lpszClassName = "newpics";  // name of window class 
	
	
	// Register the window class. 
	RegisterClassEx(&blab5);
	
textpic = CreateWindowEx(NULL,"newpics",NULL, WS_BORDER|WS_TABSTOP | WS_VISIBLE|WS_CHILD ,0,0,512,512,GetDlgItem(tMain,fraPic),0,hGlobal,0);
	
	
	ShowWindow(textpic,SW_SHOW);	
	return 0;
}

LRESULT CALLBACK TextPicProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
	HDC hdc=NULL;
	PAINTSTRUCT ps;
	switch (message) 
	{
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		TextEditor.Text.Blit(hdc, 0,0,512 ,512,0,0);
		EndPaint(hWnd, &ps);
		break;
		
  		
	}
	
    return DefWindowProc(hWnd, message, wParam, lParam);
	
}
int cTED::DecodeText(u32 offset){
//Find length of the text;
	u16 tv=0;
   
    txtlength=0;
	int i=0;
	if(GBA.ROM){
	fseek(GBA.ROM,offset,SEEK_SET);
					
							
	while(!feof(GBA.ROM)){
		fread(&tv,2,1,GBA.ROM);
        if(tv==0xFF00 || tv==0x41F) break;
		 txtlength++;
    }
	 txtlength++;
	


	fseek(GBA.ROM, offset,SEEK_SET);
	fread(binarystring,2,txtlength,GBA.ROM);
	
	memset(curtext,0,2048);
	
		for(i=0;i<txtlength;i++){//Main copy loop

			 strcat(curtext,table[binarystring[i]]);
		}
	 SetWindowText(GetDlgItem(tMain,txtString),curtext);
	
	}
	
	return 0;
}
int cTED::BiCat(u16* dest, char* entry){
	char buf[256]={0};
	int i=0, dataplus=0;//Tells how much to increase the text data
		if((entry[0]=='[')){
			
			for(i=0;i<strlen(entry);i++){
				buf[i]=entry[i];
				if((entry[i]==']')) break;
			}
			
		
			 dataplus=i;
		}else{
			buf[0]=entry[0];
			dataplus=1;
		}

		//Do a look up to match
		for(i=0;i<0xFFFF;i++){
			//compare curtext with a entry from the table then put ii into the nb stream 
			//and increase count
			if(strcmp(table[i],buf)==0){
				//They're identical so put it into stream and break; 
				*dest=i;
			 
				break;
			}
		
		}

return dataplus;

}
int cTED::EncodeText(){
    
	int i=0;
	int ii=0;//used for looking inside strings
	int iii=0;
	int itemcount=0;
	int strcounter=0;


	u16 marker=0xFF00;
	u16 nb[1024]={0};
    u32 offset=0;
	u16 returned=0;
	//GetWindowText(GetDlgItem(tMain,txtString),stupidstring,1024);
	GetWindowText(GetDlgItem(tMain,txtString),curtext,1024);
	int a = strlen(curtext);
    strcounter = 0;
	for(i=0; i<strlen(curtext);i++){
	  returned= BiCat(&binarystring[strcounter], &curtext[i]);
	  i+=(returned > 1 ? returned:0);
	  if(binarystring[strcounter]==0xFF00) break;
	  strcounter++; 

	}
     
	//Just find it a new home.
    offset= GBA.FindFreeSpace(strcounter*2,0xFF);
	fseek(GBA.ROM, offset, SEEK_SET);
	fwrite(binarystring,2,strcounter,GBA.ROM);
    fwrite(&marker,2,1,GBA.ROM);
	//Now apply changes to lists and tables
	//Offset=
	TextEditor.ZMOffsets[TextEditor.cboTxt.GetListIndex()][TextEditor.cOffsets.GetListIndex()]=offset+0x8000000;
	if(GameEngine->isZM()){
    	fseek(GBA.ROM,0x760914 ,SEEK_SET);
		for(i=0;i<99;i++) {	
			fwrite(&ZMOffsets[0][i],4,1,GBA.ROM);
			
		}
	fseek(GBA.ROM,0x760660,SEEK_SET);
		for(i=0;i<65;i++){
			fwrite(&ZMOffsets[1][i],4,1,GBA.ROM);
		
		}
      
    }else if(GameEngine->isMF()){
        fseek(GBA.ROM,0x79EA08,SEEK_SET);
		fwrite(&Offsets,4,99,GBA.ROM);
	}
	GBA.Reopen();
	    iii=cOffsets.GetListIndex(); 
		ResetList();
		cOffsets.SetListIndex(iii); 
		
		SendMessage(tMain,WM_COMMAND,LOWORD(lstOffsets),0);
	return 0;
}



int cTED::Create(){
	int i=0;
	GameEngine->OpenFile();
	FILE*fp=GameEngine->oFP();
    TextEditor.pixelflag=0;
	memset(GBA.GBAPal,0,512);
	memset(curtext,0,2048);
	cOffsets.Init(GetDlgItem(tMain,lstOffsets));
	cboTxt.Init(GetDlgItem(tMain,cboTextI));
	if(GameEngine->isZM()){
		cboTxt.Clear();
		cboTxt.Additem("Main Text");
		cboTxt.Additem("Item Text");
		cboTxt.SetListIndex(0);
		//fseek(fp,0x760914,SEEK_SET);
		//fread(&Offsets,4,99,fp);
		fseek(fp,0x415460,SEEK_SET);
		fread(&Graphics,1,0x8000,fp);
		fseek(fp,0x375738,SEEK_SET);
		fread(GBA.GBAPal,2,0x10,fp);
			fseek(fp,0x760914 ,SEEK_SET);
		for(i=0;i<99;i++) {	
			fread(&ZMOffsets[0][i],4,1,fp);
			
		}
	fseek(fp,0x760660,SEEK_SET);
		for(i=0;i<65;i++){
			fread(&ZMOffsets[1][i],4,1,fp);
		
		}
      /*  for(i=0;i<16;i++) {
			GBA.GBAPal[i*0x10]=GBA.GBAPal[i];
		 
		}*/
		GBA.DecodePal(GBA.GBAPal, FontPal,16,0);
        //for(i=0;i<16;i++)	FontPal[i*0x10]=FontPal[i];
		
    }else if(GameEngine->isMF()){
        fseek(fp,0x79EA08,SEEK_SET);
		fread(&Offsets,4,99,fp);
		fseek(fp,0x682FAC,SEEK_SET);
		fread(&Graphics,1,0x8000,fp);
		fseek(fp,0x598d0c,SEEK_SET);
		fread(&GBA.GBAPal,1,32,fp);
	    
        GBA.DecodePal(GBA.GBAPal, FontPal,16,0);
	}
   
	ResetList();
	LoadTable();
    Tiles.Load(Graphics,1024);
	Text.Create(512,512);
	Text.SetPalette(FontPal);
	CreateTextpicTileImage();
return 0; 
}
int cTED::LoadTable(){
u32 i=0;
u32 ii=0;
FILE* fp;
u32 eoff;
u32 Entry;

char buf[256];
char charbuf[256];
char ThisFileString[2048]={0};

memset(&table,0x0,sizeof(table));
for(i=0;i<0xFF00;i++)table[i][0]=0xFF;
strcpy(ThisFileString,AppPath);
strcat(ThisFileString, "\\DH.tbl");
fp = fopen(ThisFileString,"r");
if(fp){
	fseek(fp,0,SEEK_END);
	eoff=ftell(fp);
	fseek(fp,0,SEEK_SET);
	while(ftell(fp)<eoff){
    memset(buf,0,256);
	memset(charbuf,0,256);
	fgets(buf,256,fp);

	//int blah=strlen(buf);
	//buf[strlen(buf)-2]=0;
	//buf[strlen(buf)-1]=0;
	sscanf(buf,"%X=%s",&Entry,&charbuf);
	memcpy(&table[Entry],charbuf,strlen(charbuf));


	}
	table[0x40][0]=(u8)0x20;
	
	fclose(fp);
}
for(i =0;i<0xFF00;i++){

	
	if((table[i][0]==(char)0xFF)){
	
	
		  sprintf(table[i],"[RAW 0x%X]",i);
	}
}

return 0;
}



int cTED::ResetList(){
u16 i =0;
u16 max =0;
char buffer[256]={0};
GameEngine->OpenFile();
FILE* fp = GameEngine->oFP();
	if(GameEngine->isZM()){
		max=62;
	
    cOffsets.Clear();
	if(cboTxt.GetListIndex() == 0){
		for(i=0;i<99;i++) {	
		
			sprintf(buffer,"%X",ZMOffsets[0][i]);
			cOffsets.Additem(buffer);
		}
	} else {
		for(i=0;i<65;i++){
			
			sprintf(buffer,"%X",ZMOffsets[1][i]);
			cOffsets.Additem(buffer);
		}
	}
    }else if(GameEngine->isMF()){
		max=149;
        fseek(fp,0x79E6EC,SEEK_SET);
			for(i=0;i<351;i++) {
	
		fread(&Offsets[i],4,1,fp);
			sprintf(buffer,"%X",Offsets[i]);
        cOffsets.Additem(buffer);
			}
		
		
	}
		
    //for(i=0;i<62;i++){
	//	if(Offsets[i]==0) 
    //    Offsets[i]=Offsets[i];
	
	//}
	return 0;
}
